//
//  RegisterViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/7/31.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>{
    UIScrollView *scrollBG;
    UITextField *txtMoble;
    UITextField *txtCode;
    UITextField *txtPwd;
    UIButton *btnCode;
    
    BOOL boolBack;
    UIView *viewPwdBG;
    UIButton *subBtn;
}

@end

@implementation RegisterViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self tobeTouMing];
    
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=NO;
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    scrollBG=[[UIScrollView alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight)];
    [scrollBG setBackgroundColor:rgbGray];
    scrollBG.autoresizingMask=UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:scrollBG];
    
    NSInteger temp_y = 10;
    
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, temp_y, kScreenWidth, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [scrollBG addSubview:viewBG];
    [viewBG addLineLayerWhitframe:CGRectMake(0, 0, W(viewBG), 0.5) whitColor:rgbLineColor];
    [viewBG addLineLayerWhitframe:CGRectMake(0, 43.5, W(viewBG), 0.5) whitColor:rgbLineColor];
    txtMoble=[RHMethods textFieldlWithFrame:CGRectMake(10, 0, W(viewBG)-20, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入手机号" text:@""];
    [viewBG addSubview:txtMoble];
    
    temp_y+=H(viewBG)+10;
    viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, temp_y, kScreenWidth, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [scrollBG addSubview:viewBG];
    txtCode=[RHMethods textFieldlWithFrame:CGRectMake(10, 0, W(viewBG)-110, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入验证码" text:@""];
    [viewBG addSubview:txtCode];
    
    btnCode =[RHMethods buttonWithFrame:CGRectMake(XW(txtCode), 0, 100, 44) title:@"获取验证码" image:nil bgimage:nil];
    [btnCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnCode setBackgroundColor:rgbpublicColor];
    [btnCode addTarget:self action:@selector(codeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:btnCode];
    
    [viewBG addLineLayerWhitframe:CGRectMake(0, 0, W(viewBG), 0.5) whitColor:rgbLineColor];
    [viewBG addLineLayerWhitframe:CGRectMake(0, 43.5, W(viewBG), 0.5) whitColor:rgbLineColor];
    temp_y+=H(viewBG)+10;
    
     viewPwdBG=[[UIView alloc] initWithFrame:CGRectMake(0, temp_y, kScreenWidth, 44)];
    viewPwdBG.backgroundColor=[UIColor whiteColor];
    [scrollBG addSubview:viewPwdBG];
    [viewPwdBG addLineLayerWhitframe:CGRectMake(0, 0, W(viewBG), 0.5) whitColor:rgbLineColor];
    [viewPwdBG addLineLayerWhitframe:CGRectMake(0, 43.5, W(viewBG), 0.5) whitColor:rgbLineColor];
    txtPwd=[RHMethods textFieldlWithFrame:CGRectMake(10, 0, W(viewBG)-20, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入密码" text:@""];
    [txtPwd setSecureTextEntry:YES];
    [viewPwdBG addSubview:txtPwd];
    
    if (![self.userInfo isEqualToString:@"other"]) {
        temp_y+=H(viewPwdBG)+10;
    }else{
        viewPwdBG.hidden=YES;
    }
    txtMoble.delegate=self;
    txtPwd.delegate=self;
    txtCode.delegate=self;
    temp_y+=10;
    subBtn=[RHMethods buttonWithFrame:CGRectMake(10, temp_y,kScreenWidth-20, 40) title:@"确定" image:@"" bgimage:@"LoginbtnBG"];
    subBtn.titleLabel.font=Font(20);
    [subBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [subBtn addTarget:self action:@selector(submintButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [scrollBG addSubview:subBtn];
    
    temp_y+=H(subBtn)+20;
    
    [scrollBG setContentSize:CGSizeMake(kScreenWidth, temp_y)];
    
    
}
#pragma mark button
-(void)codeButtonClicked{
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"哎呀！手机号是不是没输入啊"];
        return;
    }
    [self loadSendCode:@""];
    
}

-(void)backButtonClicked:(id)sender{
    if (boolBack) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"验证码短信可能略有延迟，确定返回并重新开始？" delegate:self cancelButtonTitle:@"等待" otherButtonTitles:@"返回", nil];
        [alert show];
    }else{
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [super backButtonClicked:sender];
    }
}
-(void)submintButtonClicked{
    DLog(@"确定");//ZKpubseditpass
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    NSString *strCode=txtCode.text;
    if (![strCode notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入验证码"];
        return;
    }
    
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    [dict setValue:strTel forKey:@"mobile"];
    [dict setValue:strCode forKey:@"code"];
    NSString *strPwd=txtPwd.text;
    if (![self.userInfo isEqualToString:@"other"]) {
        if (![strPwd notEmptyOrNull]) {
            [SVProgressHUD showImage:nil status:@"请输入密码"];
            return;
        }
        [dict setValue:strPwd forKey:@"password"];
    }
    NSString *strUrl=XKFV4welcomeregister;
    if ([self.userInfo isEqualToString:@"pwd"]) {
        strUrl=XKFV4welcomeforgetpassword;
    }else if ([self.userInfo isEqualToString:@"other"]){
        strUrl=XKFV4welcomebindmobile;
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"oepnid"];
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"type"] forKey:@"type"];
    }
    [NetEngine createPostAction:strUrl withParams:dict onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
            if ([self.userInfo isEqualToString:@"pwd"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [super backButtonClicked:nil];
                });
            }else if ([self.userInfo isEqualToString:@"other"]){
                NSDictionary *userDict = [resData objectForJSONKey:@"data"];
                [[Utility Share] setUserAccount:strTel];
                [[Utility Share] setUserPwd:strPwd];
                [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
                [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
//                [[Utility Share] setUserInfo:userDict];
                [[Utility Share] saveUserInfoToDefault];
                [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[Utility Share] hiddenLoginAlert:YES];
                });
            }else{
                //注册
                NSDictionary *userDict = [resData objectForJSONKey:@"data"];
                [[Utility Share] setUserAccount:strTel];
                [[Utility Share] setUserPwd:strPwd];
                [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
                [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
//                [[Utility Share] setUserInfo:userDict];
                [[Utility Share] saveUserInfoToDefault];
                [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[Utility Share] hiddenLoginAlert:YES];
                });
            }
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
    boolBack=NO;
}

-(void)loadSendCode:(NSString *)strCid{
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    [dict setValue:strTel forKey:@"mobile"];
    
    NSString *strUrl=XKFV4welcomeregistercode;
    if ([self.userInfo isEqualToString:@"pwd"]) {
        strUrl=XKFV4welcomeforgetcode;
    }else if ([self.userInfo isEqualToString:@"other"]){
        strUrl=XKFV4welcomebindcode;
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"oepnid"];
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"type"] forKey:@"type"];
    }
    [NetEngine createHttpActionFixed:strUrl withCache:NO withParams:dict withMask:SVProgressHUDMaskTypeNone onCompletion:^(id resData, BOOL isCache) {
        DLog(@"__resData____%@",resData);
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            if ([self.userInfo isEqualToString:@"other"] &&
                [[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"pwd"] isEqualToString:@"0"]){
                viewPwdBG.hidden=NO;
                subBtn.frameY=YH(viewPwdBG)+20;
                [scrollBG setContentSize:CGSizeMake(kScreenWidth, YH(subBtn)+20)];
            }
            boolBack=YES;
            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];

            [btnCode setBackgroundColor:RGBACOLOR(150, 150, 150, 1)];
            btnCode.userInteractionEnabled=NO;
//            [self performSelector:@selector(updateButtonTitle:) withObject:@"60" afterDelay:0];
            [self performSelector:@selector(updateButtonTitle:) withObject:[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"codetime"] afterDelay:0];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
    }];
//
}

-(void)updateButtonTitle:(NSString *)str{
    float aflote=[str floatValue];
    DLog(@"________________()()()()()(");
    [btnCode setTitle:[NSString stringWithFormat:@"%.0f秒",aflote] forState:UIControlStateNormal];
    if (aflote<=1) {
        [self performSelector:@selector(yanZM_date) withObject:nil afterDelay:1.0];
    }else{
        aflote--;
        [self performSelector:@selector(updateButtonTitle:) withObject:[NSString stringWithFormat:@"%f",aflote] afterDelay:1.0];
    }
}

-(void)yanZM_date{
    DLog(@"延迟——————禁止验证码按钮");
    [btnCode setTitle:@"重新获取" forState:UIControlStateNormal];
    [btnCode setBackgroundColor:rgbpublicColor];
    btnCode.userInteractionEnabled=YES;
}
#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        boolBack=NO;
        [super backButtonClicked:nil];
    }
}

#pragma mark selector
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    
    [UIView animateWithDuration:0.3 animations:^{
        scrollBG.frame=CGRectMake(X(scrollBG), Y(scrollBG), W(scrollBG),self.view.frame.size.height- Y(scrollBG)-distanceToMove);
        
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        scrollBG.frame=CGRectMake(0, Y(scrollBG), kScreenWidth,kContentHeight);
        
        
    }];
}//

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
